/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UI;

import BO.Controller;
import BO.User;
import java.util.ArrayList;
import java.util.Date;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Ymmot
 */
public class ChatBean {
    private ArrayList<ChatView> chatList;
    private int lastMessageId;
    private String message;
    private Controller controller;
    private Date start;
    
    /** Creates a new instance of ChatBean */
    public ChatBean() {
        chatList = new ArrayList<ChatView>();
        lastMessageId = 0;
        controller = new Controller();
        start = new Date();
        message = "";
    }

    public ArrayList<ChatView> getChatList() {
        return chatList;
    }

    public void setChatList(ArrayList<ChatView> chatList) {
        this.chatList = chatList;
    }

    public ArrayList<ChatView> getNewestMessages() {
        ArrayList<ChatView> newestMessages = controller.getMessageAfter(lastMessageId, start);
        int size = newestMessages.size();
        if(size > 0){
            lastMessageId = newestMessages.get(size - 1).getId();
        }
        chatList.addAll(newestMessages);
        return chatList;
    }
    
    public void setMessage(String message){
        this.message = message;
    }
    
    public String getMessage(){
        return "";
    }
    
    public void addChatMessage(){
        //FacesContext.getCurrentInstance().getExternalContext()
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        UserView u = (UserView) session.getAttribute("user");
        controller.addChatMessage(new Date(), message, u.getId());
    }
    
    public void setFirst(){
        
    }
    
    public int getFirst(){
        int size = chatList.size();
        if(size > 10){
            size -= 10;
            return size;
        }
        return 0;
    }

    
    
    
    
    
}
